package com.allm.ai.common.config;

import java.time.Duration;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;

import com.allm.ai.common.properties.AllmAiCommonProperties;

/**
 * EnPlatform Assistant 自动配置类
 * 统一管理所有模块的配置，避免Bean定义冲突
 *
 * @author com.enplatform.assistant
 * @since 1.0.0
 */
@AutoConfiguration
@Configuration
@EnableConfigurationProperties({
    AllmAiCommonProperties.class
})
@ComponentScan(basePackages = {
    "com.allm.ai.common"
})
public class AllmAiAutoConfiguration {

    /**
     * 配置 RestTemplateBuilder Bean
     * 如果不存在则创建一个默认的
     */
    @Bean
    @ConditionalOnMissingBean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder();
    }

    /**
     * 配置主要的 RestTemplate Bean
     * 使用 @ConditionalOnMissingBean 避免重复定义
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(name = "restTemplate")
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
            .setConnectTimeout(Duration.ofSeconds(30))
            .setReadTimeout(Duration.ofSeconds(60))
            .build();
    }

    /**
     * 配置用于 AI 服务的 RestTemplate
     * 专门用于调用 AI 服务，具有更长的超时时间
     */
    @Bean("aiRestTemplate")
    @ConditionalOnMissingBean(name = "aiRestTemplate")
    public RestTemplate aiRestTemplate(RestTemplateBuilder builder, AllmAiCommonProperties properties) {
        int timeout = properties.getAi().getLocal().getTimeout();
        return builder
            .setConnectTimeout(Duration.ofMillis(timeout))
            .setReadTimeout(Duration.ofMillis(timeout * 2))
            .build();
    }

    /**
     * 配置用于向量数据库的 RestTemplate
     * 专门用于调用向量数据库服务
     */
    @Bean("vectorStoreRestTemplate")
    @ConditionalOnMissingBean(name = "vectorStoreRestTemplate")
    @ConditionalOnProperty(name = "enplatform.assistant.vectorstore.enabled", havingValue = "true", matchIfMissing = true)
    public RestTemplate vectorStoreRestTemplate(RestTemplateBuilder builder) {
        return builder
            .setConnectTimeout(Duration.ofSeconds(10))
            .setReadTimeout(Duration.ofSeconds(30))
            .build();
    }


}
